package com.canbot.u05.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.canbot.u05.MainApplication;
import com.canbot.u05.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 轮播
 */

public class ViewPagerLoop extends FrameLayout {

        private int currentIndex = 0;//viewpager当前页面

        private ArrayList<ImageView> ivs;

        private List<String> uris;

        /**
         * 自定义属性
         */
        private int delay;//间隔时间

        private boolean isLoop;//是否自动轮播

        private boolean isLoop2 = true;//用于触摸时是否自动轮播的判断

        private int orientation;//小圆点指示器的排列方向

        public static final int vertical = 1;//竖直排列

        public static final int horizontal = 2;//水平排列

        private float horDotSpace;//圆点水平间隔

        private float verDotSpace;//圆点上下间隔

        private float dotRadius;//小圆点指示器半径

        /**
         * 广告轮播布局的View
         */
        private View view;

        private RelativeLayout rlvploop;

        private RadioGroup rgdot;

        private ViewPager vploop;

        /**
         * 上下文和handler相关
         */
        private android.content.Context context;

        private Handler handler;//

        private Thread loopThread;


        public ViewPagerLoop(Context context) {
                super(context);
                initView(context);
        }

        public ViewPagerLoop(Context context, AttributeSet attrs) {
                super(context, attrs);
                initView(context);
                initData(context, attrs);
        }

        public ViewPagerLoop(Context context, AttributeSet attrs, int defStyleAttr) {
                super(context, attrs, defStyleAttr);
                initView(context);
                initData(context, attrs);
        }

        private void initView(Context context) {
                this.context = context;
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.viewpager_loop_layout, null);
                rgdot = (RadioGroup) view.findViewById(R.id.rg_dot);
                vploop = (ViewPager) view.findViewById(R.id.vp_loop);
                rlvploop = (RelativeLayout) view.findViewById(R.id.rl_vploop);
                this.addView(view);
        }

        private void initData(Context context, AttributeSet attrs) {
                TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.viewPagerLoop);
                //轮播间隔时间
                delay = typedArray.getInt(R.styleable.viewPagerLoop_interval, 3000);
                //是否自动轮播
                isLoop = typedArray.getBoolean(R.styleable.viewPagerLoop_isLoop, true);
                //小圆点指示器的排列方向
                orientation = typedArray.getInt(R.styleable.viewPagerLoop_ori, 1);
                if (orientation == vertical) {
                        rgdot.setOrientation(RadioGroup.VERTICAL);
                }
                else if (orientation == horizontal) {
                        rgdot.setOrientation(RadioGroup.HORIZONTAL);
                }
                horDotSpace = typedArray.getDimension(R.styleable.viewPagerLoop_horDotSpace, 0);
                verDotSpace = typedArray.getDimension(R.styleable.viewPagerLoop_verDotSpace, 0);
                dotRadius = typedArray.getDimension(R.styleable.viewPagerLoop_dotRadius, 7.5f);
                typedArray.recycle();
                //手指触摸时禁止自动轮播
                vploop.setOnTouchListener(new OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                                ViewPagerLoop.super.onTouchEvent(event);
                                switch (event.getAction()) {
                                        case MotionEvent.ACTION_DOWN:
                                                isLoop2 = false;
                                                break;
                                        case MotionEvent.ACTION_UP:
                                                isLoop2 = true;
                                                break;
                                }
                                return false;
                        }
                });
        }

        /**
         * 初始化轮播数据
         *
         * @param uriList
         */
        public void startVpSlide(final List<String> uriList) {
                VpLoopAdapter adapter = new VpLoopAdapter(initImage(uriList));
                vploop.setAdapter(adapter);
                final int childCount = uriList.size();
                if (childCount <= 0) {
                        try {
                                throw new IllegalAccessException("divide by zero");
                        }
                        catch (IllegalAccessException e) {
                                e.printStackTrace();
                        }
                        return;
                }
                Context context = vploop.getContext();
                for (int i = 0; i < childCount; i++) {
                        RadioButton rb = new RadioButton(context);
                        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams((int) (2 * dotRadius), (int) (2 * dotRadius));
                        params.setMargins((int) horDotSpace, (int) verDotSpace, 0, 0);
                        rb.setLayoutParams(params);
                        Drawable drawable = context.getResources().getDrawable(R.drawable.radiobutton_drawable);
                        rb.setEnabled(false);
                        rb.setButtonDrawable(new BitmapDrawable());
                        rb.setBackground(drawable);
                        rgdot.addView(rb);
                }
                if (rgdot.getChildCount() == 0) {
                        try {
                                throw new IllegalAccessException("RadioGroup no child");
                        }
                        catch (IllegalAccessException e) {
                                e.printStackTrace();
                                return;
                        }
                }
                else {
                        RadioButton rb = (RadioButton) rgdot.getChildAt(0);
                        rb.setChecked(true);
                }
                vploop.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                                RadioButton rb = (RadioButton) rgdot.getChildAt(position % uriList.size());
                                rb.setChecked(true);
                                currentIndex = position;
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                });
                vploop.setCurrentItem(childCount * 20000);

                handler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                                if (isLoop2 == false) {
                                        return;
                                }
                                if (msg.what == 1) {
                                        vploop.setCurrentItem(currentIndex);
                                        RadioButton rb = (RadioButton) rgdot.getChildAt(currentIndex % childCount);
                                        rb.setChecked(true);
                                        currentIndex++;
                                }
                        }
                };
                loopThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                                while (true) {
                                        SystemClock.sleep(delay);
                                        handler.sendEmptyMessage(1);
                                }
                        }
                });
                if (isLoop == true) {
                        loopThread.start();
                }
        }

        /**
         * 是否自动轮播
         *
         * @param isLoop
         */
        public void isLoop(boolean isLoop) {
                this.isLoop = isLoop;
                if (isLoop == true) {
                        loopThread.start();
                }
                else {
                        loopThread.interrupt();
                }
        }

        /**
         * 设置轮播间隔时间
         *
         * @param delay
         */
        public void setLoopDelay(int delay) {
                this.delay = delay;
        }

        /**
         * @return
         */
        public ViewPager getViewPager() {
                return vploop;
        }

        /**
         * @return
         */
        public RadioGroup getRgdot() {
                return rgdot;
        }

        /**
         * @return
         */
        public RelativeLayout getRlvploop() {
                return rlvploop;
        }

        private ArrayList<ImageView> initImage(List<String> uris) {
                ArrayList<ImageView> imageViews = new ArrayList<>();
//        /*
//        * universal imageLoader framework
//        * */
//        ImageLoader instance = ImageLoader.newInstance();
//        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() //
//                .showImageForEmptyUri(R.drawable.fail_load_image) //
//                .showImageOnFail(R.drawable.fail_load_image) //
//                .cacheInMemory(true) //
//                .cacheOnDisk(true) //
//                .build();//
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration//
//                .Builder(context)//
//                .defaultDisplayImageOptions(defaultOptions)//
//                .writeDebugLogs()//
//                .build();//
//        instance.init(config);

                for (int i = 0; i < uris.size(); i++) {
                        ImageView imageView = new ImageView(context);
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        MainApplication.instance.displayImage(uris.get(i), imageView);
                        imageViews.add(imageView);
                }
                return imageViews;
        }

        public ArrayList<ImageView> getIvs() {
                return ivs;
        }

        public void setIvs(ArrayList<ImageView> ivs) {
                this.ivs = ivs;
        }

        public List<String> getUris() {
                return uris;
        }

        public void setUris(List<String> uris) {
                startVpSlide(uris);
        }

        //Viewpge适配器
        public class VpLoopAdapter extends PagerAdapter {

                public VpLoopAdapter(List<ImageView> imageViews) {
                        this.imageViews = imageViews;
                        if (imageViews == null) {
                                this.imageViews = new ArrayList<>();
                        }
                }

                private List<ImageView> imageViews;

                @Override
                public int getCount() {
                        return imageViews.size() != 0 ? Integer.MAX_VALUE : 0;
                }

                @Override
                public boolean isViewFromObject(View view, Object object) {
                        return view == object;
                }

                @Override
                public Object instantiateItem(ViewGroup container, int position) {
                        ImageView view = imageViews.get(position % imageViews.size());
                        container.addView(view);
                        return view;
                }

                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                        container.removeView((View) object);
                }
        }


}
